﻿using GpCommon;
using GpCommon.Helpers;
using GpCommon.Models;
using GPSpeedView.GPHelpers;
using GPSpeedView.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace GPSpeedView.Views
{
    /// <summary>
    /// AIAutoHandleView.xaml 的交互逻辑
    /// </summary>
    public partial class AIAutoHandleView : Window
    {
        private AiAutoHandleVModel m_VModel;
        public AIAutoHandleView()
        {
            InitializeComponent();
            m_VModel = new AiAutoHandleVModel(this);
            this.DataContext = m_VModel;
        }

        private void checkBtn_Click(object sender, RoutedEventArgs e)
        {
            this.listBox.SelectedIndex = listBox.Items.Count - 1;
        }
    }

    public class AiAutoHandleVModel : BindableBase
    {
        public BackgroundWorker worker;
        public string barMsg;
        public int infoNum;
        private AIAutoHandleView m_View;

        private Dictionary<DateTime, List<GpDayEntity>> dicGpInfo = new Dictionary<DateTime, List<GpDayEntity>>();
        private Dictionary<string, List<GpDayEntity>> dicAllGpInfo = new Dictionary<string, List<GpDayEntity>>();

        public AccountEntity m_Account;
        public float TotalValue;
        public int TotalRunCount;
        private bool hasChangeYear = false;
        private List<string> m_SelectedCodes = new List<string>();

        private ObservableCollection<string> m_MsgList = new ObservableCollection<string>();

        public ObservableCollection<string> MsgList
        {
            get { return m_MsgList; }
            set
            {
                m_MsgList = value;
                RaisePropertyChanged();
            }
        }

        private int m_Cash = 10000;

        public int Cash
        {
            get { return m_Cash; }
            set
            {
                m_Cash = value;
                RaisePropertyChanged();
            }
        }
        private int m_ValidGpNum = 1;

        public int ValidGpNum
        {
            get { return m_ValidGpNum; }
            set
            {
                m_ValidGpNum = value;
                RaisePropertyChanged();
            }
        }
        private int m_CurYear = 2024;

        public int CurYear
        {
            get { return m_CurYear; }
            set
            {
                if (m_CurYear != value)
                    hasChangeYear = true;
                m_CurYear = value;
                RaisePropertyChanged();
            }
        }
        private string m_SpecialCodes;

        public string SpecialCodes
        {
            get { return m_SpecialCodes; }
            set
            {
                m_SpecialCodes = value;
                RaisePropertyChanged();
            }
        }

        private string m_SpecialMonth;

        public string SpecialMonth
        {
            get { return m_SpecialMonth; }
            set
            {
                m_SpecialMonth = value;
                RaisePropertyChanged();
            }
        }

        private string m_SpecialDay;

        public string SpecialDay
        {
            get { return m_SpecialDay; }
            set
            {
                m_SpecialDay = value;
                RaisePropertyChanged();
            }
        }
        public ICommand RunCommand { get; set; }
        public AiAutoHandleVModel(AIAutoHandleView view)
        {
            m_View = view;
            InitCommand();
            m_Account = new AccountEntity { Cash = 200000, ValidBuyNum = 2 };


            //worker = new BackgroundWorker();
            //worker.WorkerReportsProgress = true;
            //worker.ProgressChanged += Worker_ProgressChanged;
            //worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
            //worker.DoWork += Run;
            //Thread thread = new Thread(Run);
            //thread.Start();
        }

        #region 模拟流程
        private void SimpleAutoExecute(DateTime time, ref List<string> IntentionList)
        {

            #region 已有持仓，判断是否处理
            for (int i = 0; i < m_Account.CurBuyInGps.Count; i++)
            {
                var temp = m_Account.CurBuyInGps[i];
                var nowEnt = dicAllGpInfo[temp.GpCode].Find(x => x.Time == time);
                if (nowEnt == null) continue;
                int nowIndex = dicAllGpInfo[temp.GpCode].IndexOf(nowEnt);
                if (nowIndex <= 0) continue;
                var yesEnt = dicAllGpInfo[temp.GpCode][nowIndex - 1];

                var ms5Ent = GpLocalDataHelper.GetDay5MSEntitiesByCode(time.Year, temp.GpCode);

                // 1. 始终未击破均线，1:30分前有涨停，涨停后未开板，持有
                // 2. 始终未击破均线, 1:30分前有涨停，后有开板，2:30分前有涨停，卖出，否则该时刻卖出
                // 3. 始终未击破均线, 1:30分前无涨停，2:30分卖出
                // 4. 有击破，短时拉回，等待拉升，7个点可以卖出，2:30分前卖出
                // 5. 有击破，未拉回，直接卖
                // 6. 开盘5分内始终低于均线，卖
                DateTime startTime = new DateTime(time.Year, time.Month, time.Day, 9, 35, 0);
                DateTime endTime = new DateTime(time.Year, time.Month, time.Day, 14, 30, 0);
                if (ms5Ent.Find(x => x.CurTime == startTime) == null) continue;
                //float midOffset = yesEnt.ClsPrice * 0.01f;  // 击破程度，1个点
                float midOffset = 0f;  // 击破程度，1个点
                bool hasBreakDownToMid = false;
                bool hasBreakDownLastFive = false;
                bool isTopNoDown = true;
                bool hasTop = false;
                do
                {
                    var gpTemp = ms5Ent.Find(x => x.CurTime == startTime);

                    if (hasBreakDownLastFive)
                    {
                        // 有击破，未拉回，直接卖
                        if (gpTemp.EndPrice < gpTemp.MidPrice)
                        {
                            PayOutGp(temp, gpTemp.EndPrice, startTime);
                            i--;
                            break;
                        }
                        else
                        {
                            hasBreakDownLastFive = false;
                        }
                    }
                    if (hasBreakDownToMid)
                    {
                        // 有击破，短时拉回，等待拉升，7个点可以卖出
                        if ((gpTemp.EndPrice - yesEnt.ClsPrice) / yesEnt.ClsPrice > 0.07f)
                        {
                            PayOutGp(temp, gpTemp.EndPrice, startTime);
                            i--;
                            break;
                        }
                    }
                    if (gpTemp.EndPrice < gpTemp.MidPrice - midOffset)
                    {
                        // 击破均线
                        hasBreakDownToMid = true;
                        hasBreakDownLastFive = true;
                    }
                    if (startTime <= new DateTime(time.Year, time.Month, time.Day, 13, 30, 0))
                    {
                        if ((gpTemp.EndPrice - yesEnt.ClsPrice) / yesEnt.ClsPrice > 0.095f)
                        {
                            hasTop = true;
                        }
                        else
                        {
                            if (hasTop)
                                isTopNoDown = false;
                            hasTop = false;
                        }
                    }

                    // 始终未击破均线, 1:30分前有涨停，后有开板，2:30分前有涨停，卖出，否则该时刻卖出
                    if (!isTopNoDown && hasTop)
                    {
                        PayOutGp(temp, gpTemp.EndPrice, startTime);
                        i--;
                        break;
                    }

                    if (startTime == new DateTime(time.Year, time.Month, time.Day, 9, 35, 0))
                    {
                        // 开盘5分内始终低于均线，卖
                        if (gpTemp.EndPrice < gpTemp.MidPrice && gpTemp.HighPrice <= gpTemp.StartPrice)
                        {
                            PayOutGp(temp, gpTemp.EndPrice, startTime);
                            i--;
                            break;
                        }
                    }

                    if (startTime == endTime)
                    {
                        //  始终未击破均线，1:30分前有涨停，涨停后未开板，持有
                        if (hasTop && isTopNoDown) break;

                        PayOutGp(temp, gpTemp.EndPrice, startTime);
                        i--;
                        break;
                    }
                    if (startTime == new DateTime(time.Year, time.Month, time.Day, 11, 30, 0))
                    {
                        startTime = new DateTime(time.Year, time.Month, time.Day, 13, 5, 0);
                    }
                    else
                    {
                        startTime = startTime.AddMinutes(5);
                    }
                } while (DateTime.Compare(startTime, endTime) <= 0);

                #region 暂时注释
                //var gp935 = ms5Ent.Find(x => x.CurTime == tempTime);
                //if (gp935 == null) continue;
                ////五分钟为下跌，卖
                //if (gp935.EndPrice < gp935.StartPrice)
                //{
                //    PayOutGp(temp, gp935.EndPrice, time);
                //    i--;
                //    continue;
                //}

                //// 10点半前出现低于均线值情况，卖掉
                //DateTime targetTime = new DateTime(time.Year, time.Month, time.Day, 10, 30, 0);
                //bool hasPay = false;
                //do
                //{
                //    tempTime = tempTime.AddMinutes(5);
                //    var curEnt = ms5Ent.Find(x => x.CurTime == tempTime);
                //    if (curEnt.EndPrice < curEnt.MidPrice)
                //    {
                //        PayOutGp(temp, curEnt.EndPrice, time);
                //        i--;
                //        hasPay = true;
                //        break;
                //    }

                //} while (DateTime.Compare(tempTime, targetTime) < 0);
                //if (hasPay) continue;

                ////// 低开 10点前有下跌就卖出
                ////if(nowEnt.PrePrice < yesEnt.ClsPrice)
                ////{
                ////    bool hasPay = false;
                ////    int minu = 40;
                ////    GpDayMSEntity lastEnt = gp935;
                ////    do
                ////    {
                ////        tempTime = new DateTime(time.Year, time.Month, time.Day, 9, minu, 0);
                ////        var curEnt = ms5Ent.Find(x => x.CurTime == tempTime);
                ////        if(curEnt.EndPrice < lastEnt.EndPrice)
                ////        {
                ////            PayOutGp(temp, curEnt.EndPrice, time);
                ////            i--;
                ////            hasPay = true;
                ////            break;
                ////        }
                ////        minu += 5;

                ////    } while (minu < 60);
                ////    if (hasPay) continue;
                ////}
                ////tempTime = new DateTime(time.Year, time.Month, time.Day, 10, 0, 0);
                ////var gp100 = ms5Ent.Find(x => x.CurTime == tempTime);
                ////// 10点股价低于开盘，卖掉
                ////if(gp100.EndPrice < nowEnt.PrePrice)
                ////{
                ////    PayOutGp(temp, gp100.EndPrice, time);
                ////    i--;
                ////    continue;
                ////}
                ////tempTime = new DateTime(time.Year, time.Month, time.Day, 10, 10, 0);
                ////var gp1010 = ms5Ent.Find(x => x.CurTime == tempTime);
                ////if(gp1010.EndPrice <= gp100.EndPrice)
                ////{
                ////    PayOutGp(temp, gp1010.EndPrice, time);
                ////    i--;
                ////    continue;
                ////}

                //tempTime = new DateTime(time.Year, time.Month, time.Day, 14, 30, 0);
                //var gp1430 = ms5Ent.Find(x => x.CurTime == tempTime);
                //// 指定时刻未涨停，卖掉
                //if (gp1430.EndPrice < yesEnt.ClsPrice * (1 + 0.09))
                //{
                //    PayOutGp(temp, gp1430.EndPrice, time);
                //    i--;
                //    continue;
                //}
                #endregion
            }
            #endregion
            #region 本日满仓，不买入，清除昨日意向
            if (m_Account.CurBuyInGps.Count == m_Account.ValidBuyNum)
            {
                IntentionList.Clear();
            }
            #endregion

            #region 无意向，本日添加意向，无操作
            if (IntentionList.Count == 0)
            {
                foreach (var item in dicGpInfo[time])
                {

                    var nowGp = dicAllGpInfo[item.Code].Find(x => x.Time == time);
                    if (nowGp == null) continue;
                    int indexNow = dicAllGpInfo[item.Code].IndexOf(nowGp);
                    if (indexNow <= 0) continue;
                    var yesGp = dicAllGpInfo[item.Code][indexNow - 1];

                    //一字板次日不买
                    if (item.MarkUp > 9.5 &&
                        (item.Amplitude < 1 || (item.ClsPrice - item.PrePrice) / item.PrePrice < 0.02))
                        continue;
                    if (EnableForTopOneDay)
                    {
                        // 当日涨停
                        if (item.MarkUp > 9.5)
                        {
                            IntentionList.Add(item.Code);
                        }
                    }
                    if (EnableForTopOneDayWithNiceHistory)
                    {
                        // 当日涨停并且前100交易日无首板下跌
                        if (item.MarkUp > 9.5 && !HasOneTopDown(item.Code, time))
                        {
                            IntentionList.Add(item.Code);
                        }
                    }
                    if (EnableForTopTwoDay)
                    {
                        // 连续两天涨停
                        if (item.MarkUp > 9.5 && yesGp.MarkUp > 9.5)
                        {
                            IntentionList.Add(item.Code);
                        }
                    }
                }
                return;
            }
            #endregion
            #region 择机买入操作
            Dictionary<float, string> highDicGp = new Dictionary<float, string>();
            List<Tuple<DateTime, string, float>> buyList = new List<Tuple<DateTime, string, float>>();
            Random random = new Random();
            IntentionList = IntentionList.OrderBy(x => random.Next()).ToList();

            foreach (var item in IntentionList)
            {
                var nowGp = dicAllGpInfo[item].Find(x => x.Time == time);
                if (nowGp == null) continue;
                int indexNow = dicAllGpInfo[item].IndexOf(nowGp);

                var yesGp = dicAllGpInfo[item][indexNow - 1];
                if (nowGp.PrePrice < yesGp.ClsPrice)
                    continue;


                var preMarkUp = (nowGp.PrePrice - yesGp.ClsPrice) * 100.0 / yesGp.ClsPrice;
                // 开盘绿盘，跳过
                if (EnableForLowStart && preMarkUp < 0) continue;

                var ms5Ent = GpLocalDataHelper.GetDay5MSEntitiesByCode(time.Year, item);
                if (ms5Ent == null || ms5Ent.Count == 0) continue;

                DateTime tempTime = new DateTime(time.Year, time.Month, time.Day, 9, 35, 0);
                float buyPriceInPlan = nowGp.PrePrice;
                DateTime buyTime = tempTime;
                if (EnableForMarkDownInFive)
                {
                    var gp935 = ms5Ent.Find(x => x.CurTime == tempTime);
                    if (gp935 == null) continue;
                    // 五分钟为上涨，
                    if (gp935.EndPrice <= gp935.StartPrice) continue;
                    buyPriceInPlan = gp935.EndPrice;
                }

                if (EnableForBreakDownInFive)
                {
                    var gp935 = ms5Ent.Find(x => x.CurTime == tempTime);
                    if (gp935 == null) continue;
                    // 五分钟跌破均线，
                    if (gp935.MidPrice > gp935.EndPrice) continue;
                    buyPriceInPlan = gp935.EndPrice;
                }

                if (EnableForBreakDownInTen)
                {
                    // 十分钟跌破均线
                    tempTime = new DateTime(time.Year, time.Month, time.Day, 9, 40, 0);
                    var gp940 = ms5Ent.Find(x => x.CurTime == tempTime);
                    if (EnableForBreakDownInTen && gp940.MidPrice > gp940.EndPrice) continue;
                    buyPriceInPlan = gp940.EndPrice;
                    buyTime = tempTime;
                }

                //// 五分钟跌破均线，看十分钟是否站上均线，站不上就跳过
                //if (gp935.MidPrice > gp935.EndPrice)
                //{
                //    tempTime = new DateTime(time.Year, time.Month, time.Day, 9, 40, 0);
                //    var gp940 = ms5Ent.Find(x => x.CurTime == tempTime);
                //    if (gp940.MidPrice > gp940.EndPrice)
                //        continue;
                //    buyPriceInPlan = gp940.EndPrice;
                //}

                // 开盘涨幅2-7
                if (EnableForStartIn2_7 && (preMarkUp < 2 || preMarkUp >= 7)) continue;

                // 如果已涨停，跳过
                if ((buyPriceInPlan - yesGp.ClsPrice) / yesGp.ClsPrice > 0.095) continue;

                buyList.Add(new Tuple<DateTime, string, float>(buyTime, item, buyPriceInPlan));
                //var tempMarkUp = (buyPriceInPlan - nowGp.PrePrice) / nowGp.PrePrice;
                //highDicGp.Add(tempMarkUp, item);
            }
            IntentionList.Clear();
            foreach (var item in buyList)
            {
                if (m_Account.CurBuyInGps.Count >= m_Account.ValidBuyNum)
                    return;
                int validNum = m_Account.ValidBuyNum - m_Account.CurBuyInGps.Count;
                double curCash = Math.Floor(m_Account.Cash / (double)validNum);
                var tempGp = dicGpInfo[time].Find(x => x.Code == item.Item2);
                //float buyPrice = tempGp.PrePrice * (1 + item.Key);
                //buyPrice = float.Parse(buyPrice.ToString("F2"));
                float buyPrice = item.Item3;
                int count = (int)Math.Floor(curCash / (buyPrice * 100)) * 100;
                if (count == 0) continue;
                BuyGp(item.Item2, tempGp.Name, buyPrice, count, item.Item1);
            }
            #endregion
        }

        /// <summary>
        /// 持有股票处理
        /// </summary>
        /// <param name="time"></param>
        private void PossessGpExecute(DateTime time)
        {

            for (int i = 0; i < m_Account.CurBuyInGps.Count; i++)
            {
                var temp = m_Account.CurBuyInGps[i];
                var nowEnt = dicAllGpInfo[temp.GpCode].Find(x => x.Time == time);
                if (nowEnt == null) continue;
                int nowIndex = dicAllGpInfo[temp.GpCode].IndexOf(nowEnt);
                if (nowIndex <= 0) continue;
                var yesEnt = dicAllGpInfo[temp.GpCode][nowIndex - 1];

                float m95Price = yesEnt.ClsPrice * 1.095f;
                float m98Price = yesEnt.ClsPrice * 1.098f;
                float m2Price = yesEnt.ClsPrice * 1.02f;
                float m5Price = yesEnt.ClsPrice * 1.05f;

                #region 规则1
                //// 除一字板或五分钟内涨停，卖
                //if (nowEnt.MarkUp > 9.5 && nowEnt.Amplitude < 1)
                //    continue;
                //var list = AlGpHelper.GetDayMS_OLEntityByCode(time, temp.GpCode).Result;
                //if (list.Count == 0) continue;
                //var pre5List = list.GetRange(0, 5);
                //var aft5List = list.GetRange(6, list.Count - 6);
                //if (pre5List.Find(x => x.Price >= m95Price) != null
                //    && aft5List.Find(x => x.Price <= m95Price) != null)
                //    continue;


                //PayOutGp(temp, nowEnt.ClsPrice, list[120].Time);
                //i--;
                #endregion

                #region 规则2
                //var ms1Ent = AlGpHelper.GetDayMS_OLEntityByCode(time, temp.GpCode).Result;

                //if (ms1Ent == null) continue;
                //// 1. 始终未击破均线，1:30分前有涨停，涨停后未开板，持有
                //// 2. 始终未击破均线, 1:30分前有涨停，后有开板，2:30分前有涨停，卖出，否则该时刻卖出
                //// 3. 始终未击破均线, 1:30分前无涨停，2:30分卖出
                //// 4. 有击破，短时拉回，等待拉升，7个点可以卖出，2:30分前卖出
                //// 5. 有击破，未拉回，直接卖
                //// 6. 开盘5分内始终低于均线，卖
                //DateTime startTime = new DateTime(time.Year, time.Month, time.Day, 9, 35, 0);
                //DateTime endTime = new DateTime(time.Year, time.Month, time.Day, 14, 30, 0);
                //if (ms1Ent.Find(x => x.Time == startTime) == null) continue;
                ////float midOffset = yesEnt.ClsPrice * 0.01f;  // 击破程度，1个点
                //float midOffset = 0f;  // 击破程度，1个点
                //bool hasBreakDownToMid = false;
                //bool hasBreakDownLastFive = false;
                //bool isTopNoDown = true;
                //bool hasTop = false;
                //do
                //{
                //    var gpTemp = ms1Ent.Find(x => x.Time == startTime);

                //    if (hasBreakDownLastFive)
                //    {
                //        // 有击破，未拉回，直接卖
                //        if (gpTemp.Price < gpTemp.MidPrice)
                //        {
                //            PayOutGp(temp, gpTemp.Price, startTime);
                //            i--;
                //            break;
                //        }
                //        else
                //        {
                //            hasBreakDownLastFive = false;
                //        }
                //    }
                //    if (hasBreakDownToMid)
                //    {
                //        // 有击破，短时拉回，等待拉升，7个点可以卖出
                //        if ((gpTemp.Price - yesEnt.ClsPrice) / yesEnt.ClsPrice > 0.07f)
                //        {
                //            PayOutGp(temp, gpTemp.Price, startTime);
                //            i--;
                //            break;
                //        }
                //    }
                //    if (gpTemp.Price < gpTemp.MidPrice - midOffset)
                //    {
                //        // 击破均线
                //        hasBreakDownToMid = true;
                //        hasBreakDownLastFive = true;
                //    }
                //    if (startTime <= new DateTime(time.Year, time.Month, time.Day, 13, 30, 0))
                //    {
                //        if ((gpTemp.Price - yesEnt.ClsPrice) / yesEnt.ClsPrice > 0.095f)
                //        {
                //            hasTop = true;
                //        }
                //        else
                //        {
                //            if (hasTop)
                //                isTopNoDown = false;
                //            hasTop = false;
                //        }
                //    }

                //    // 始终未击破均线, 1:30分前有涨停，后有开板，2:30分前有涨停，卖出，否则该时刻卖出
                //    if (!isTopNoDown && hasTop)
                //    {
                //        PayOutGp(temp, gpTemp.Price, startTime);
                //        i--;
                //        break;
                //    }

                //    if (startTime == new DateTime(time.Year, time.Month, time.Day, 9, 35, 0))
                //    {
                //        // 开盘5分内始终低于均线，卖
                //        if (gpTemp.Price < gpTemp.MidPrice)
                //        {
                //            PayOutGp(temp, gpTemp.Price, startTime);
                //            i--;
                //            break;
                //        }
                //    }

                //    if (startTime == endTime)
                //    {
                //        //  始终未击破均线，1:30分前有涨停，涨停后未开板，持有
                //        if (hasTop && isTopNoDown) break;

                //        PayOutGp(temp, gpTemp.Price, startTime);
                //        i--;
                //        break;
                //    }
                //    if (startTime == new DateTime(time.Year, time.Month, time.Day, 11, 30, 0))
                //    {
                //        startTime = new DateTime(time.Year, time.Month, time.Day, 13, 5, 0);
                //    }
                //    else
                //    {
                //        startTime = startTime.AddMinutes(5);
                //    }
                //} while (DateTime.Compare(startTime, endTime) <= 0);

                #endregion

                #region 规则3
                ////卖出要点
                ////1.次日开盘高开并且五分内涨停，继续持有
                ////2. 35分到十点红盘，逢高出
                ////3.全天有红盘，逢高出
                ////4.全天无红盘，继续持有，最多持有三天，跌幅超10点，出，中间翻红就出
                //if(temp.BuyInDay == 1 && yesEnt.MarkUp < 9.5)
                //{
                //    PayOutGp(temp, nowEnt.PrePrice, nowEnt.Time);
                //    i--;
                //    continue;
                //}
                //if(temp.BuyInDay > 1 && yesEnt.ClsPrice < temp.BuyInPrice)
                //{
                //    if(nowEnt.HighPrice > temp.BuyInPrice)
                //    {
                //        PayOutGp(temp, nowEnt.HighPrice, nowEnt.Time);
                //        i--;
                //        continue;
                //    }
                //    if (temp.BuyInDay >= 5 || nowEnt.LowPrice < temp.BuyInPrice * 0.9f)
                //    {
                //        PayOutGp(temp, nowEnt.HighPrice, nowEnt.Time);
                //        i--;
                //        continue;
                //    }
                //    continue;
                //}



                //if (nowEnt.MarkUp > 9.5 && nowEnt.Amplitude < 1)
                //    continue;
                //var list = GpLocalDataHelper.GetDay1MSEntitiesByCode(time.Year, temp.GpCode);
                //DateTime todtime931 = new DateTime(time.Year, time.Month, time.Day, 9, 31, 0);
                //var tod931Index = list.FindIndex(x => x.CurTime == todtime931);
                //if (tod931Index < 0) continue;
                //list = list.GetRange(tod931Index, 240);

                //if (temp.BuyInDay > 1 && yesEnt.MarkUp > 9.5 && yesEnt.Amplitude < 1)
                //{
                //    PayOutGp(temp, list[0].EndPrice, list[0].CurTime);
                //    i--;
                //    continue;
                //}

                //if (list[0].EndPrice > m2Price)
                //{
                //    if(list.GetRange(0, 5).Find(x => x.EndPrice > m95Price) != null)
                //    {
                //        var payOutEnt = list.GetRange(5, list.Count - 5).FirstOrDefault(x => x.EndPrice < m95Price);
                //        if(payOutEnt != null)
                //        {
                //            PayOutGp(temp, payOutEnt.EndPrice, payOutEnt.CurTime);
                //            i--;
                //            continue;
                //        }
                //    }
                //}
                //var list36_End = list.GetRange(36, list.Count - 36);
                //var fstIndex = list36_End.FindIndex(x => x.EndPrice > yesEnt.ClsPrice);
                //if(fstIndex >= 0)
                //{
                //    int tempIndex = fstIndex;
                //    do
                //    {
                //        tempIndex += 2;
                //    } while (tempIndex < list36_End.Count && list36_End[tempIndex].EndPrice >= list36_End[tempIndex - 2].EndPrice);

                //    PayOutGp(temp, list36_End[tempIndex - 2].EndPrice, list36_End[tempIndex - 2].CurTime);
                //    i--;
                //    continue;
                //}



                #endregion

                #region 规则4
                // 如有涨停，只要开板就卖
                // 前日未涨停，开盘卖
                // 收盘卖
                if (nowEnt.MarkUp >= 9.8) continue;
                if(yesEnt.MarkUp < 9.8 && nowEnt.PrePrice < m98Price)
                {
                    PayOutGp(temp, nowEnt.PrePrice, nowEnt.Time);
                    i--;
                    continue;
                }
                if(nowEnt.HighPrice >= m98Price)
                {
                    PayOutGp(temp, nowEnt.HighPrice, nowEnt.Time);
                    i--;
                    continue;
                }
                PayOutGp(temp, nowEnt.ClsPrice, nowEnt.Time);
                i--;
                continue;


                #endregion
            }

            m_Account.CurBuyInGps.ForEach(x => x.BuyInDay += 1);
        }
        /// <summary>
        /// 股票买入处理
        /// </summary>
        /// <param name="time"></param>
        private void SelectToBuyExecute(DateTime time)
        {
            if (m_Account.CurBuyInGps.Count >= m_Account.ValidBuyNum)
                return;
            List<Tuple<DateTime, string, float>> buyList = new List<Tuple<DateTime, string, float>>();

            foreach (var item in dicGpInfo[time])
            {
                if(m_SelectedCodes.Count != 0 && !m_SelectedCodes.Contains(item.Code))
                {
                    continue;
                }
                var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item.Code);
                if (dayEnts == null) continue;
                var nowIndex = dayEnts.FindIndex(x => x.Time.Month == time.Month && x.Time.Day == time.Day);
                #region 规则1
                //// 四板逻辑
                //// 1. 连续四天涨停
                //// 2. 第四天一字板不买
                //// 3. 第五天涨停开盘不买，跌停开盘不买
                //// 4. 第五天开盘快速下杀，可买跌停位
                //// 5. 第五天开盘无快速下杀，速买
                //if (nowIndex < 4) continue;
                //var pre4List = dayEnts.GetRange(nowIndex - 3, 3);
                //if (pre4List.Find(x => x.MarkUp < 9.5) != null) continue;
                //if (dayEnts[nowIndex - 4].MarkUp > 9.5) continue;

                //if (dayEnts[nowIndex - 1].Amplitude < 1) continue;

                //float m95Price = dayEnts[nowIndex - 1].ClsPrice * 1.095f;
                //float m_95Price = dayEnts[nowIndex - 1].ClsPrice * 0.905f;

                //if (dayEnts[nowIndex].PrePrice > m95Price || dayEnts[nowIndex].PrePrice < m_95Price) continue;

                //var list = AlGpHelper.GetDayMS_OLEntityByCode(time, item.Code).Result;
                //if (list.Count == 0) continue;
                //if (dayEnts[nowIndex].PrePrice > list[0].Price
                //    && list[0].Price > list[1].Price) continue;
                //if (list[1].Price > m95Price) continue;

                //buyList.Add(new Tuple<DateTime, string, float>(list[1].Time, item.Code, list[1].Price));
                //continue;
                #endregion

                #region 规则2
                ///// 买入原则：
                ///// 1. 多头上升，均线上升或者均线水平（前期为下降趋势）
                ///// 2. 开盘低开2个点以上，过滤
                ///// 3. 高开且开盘3分钟迅速拉升到8个点以上，可考虑介入
                ///// 4. 十点后均未击破均线，或者始终在±1.5浮动，5点以下买入
                ///// 
                //if (nowIndex < 2) continue;

                //// 首日涨停
                //if (dayEnts[nowIndex - 1].MarkUp < 9.5 || dayEnts[nowIndex - 2].MarkUp > 9.5)
                //    continue;

                //// 一字涨停，不追
                //if (dayEnts[nowIndex - 1].Amplitude < 2) continue;
                ////// 60日线上涨趋势
                ////if (dayEnts[nowIndex - 1].Day60Price < dayEnts[nowIndex - 2].Day60Price) continue;

                //if (!AlGpHelper.HasHighChance2(item.Code, dayEnts[nowIndex - 1].Time))
                //    continue;

                //if (nowIndex > 20)
                //{
                //    var tempList = dayEnts.GetRange(nowIndex - 20, 20);
                //    if (tempList.FindAll(x => x.MarkUp > 9.5).Count >= 3) continue;
                //}

                //var price00P = dayEnts[nowIndex - 1].ClsPrice;
                //var price095P = (float)Math.Round(price00P * 1.095, 2);
                //var price02DP = (float)Math.Round(price00P * 0.98, 2);
                //var price020P = (float)Math.Round(price00P * 1.02, 2);
                //var price030P = (float)Math.Round(price00P * 1.03, 2);
                //var price050P = (float)Math.Round(price00P * 1.05, 2);

                //var ms1Ents = AlGpHelper.GetDay1MSEntitiesByCode(time.Year, item.Code);
                //if (ms1Ents == null) continue;
                //var yestime = dayEnts[nowIndex - 1].Time;
                //DateTime yestime931 = new DateTime(yestime.Year, yestime.Month, yestime.Day, 9, 31, 0);
                //var yes931Index = ms1Ents.FindIndex(x => x.CurTime == yestime931);
                //if (yes931Index < 0) continue;
                //var yesList = ms1Ents.GetRange(yes931Index, 240);
                //// 昨日尾盘涨停，不追
                //var yesprice00P = dayEnts[nowIndex - 2].ClsPrice;
                //var yesprice095P = (float)Math.Round(yesprice00P * 1.095, 2);

                //var yesUpIndex = yesList.FindIndex(x => x.EndPrice > yesprice095P);
                //if (yesUpIndex < 0 || yesUpIndex > 210) continue;
                //yesUpIndex++;
                //yesList = yesList.GetRange(yesUpIndex, yesList.Count - yesUpIndex);
                //// 中途开板，跳过
                //if (yesList.Find(x => x.EndPrice <= yesprice095P) != null) continue;

                //DateTime time931 = new DateTime(time.Year, time.Month, time.Day, 9, 31, 0);
                //var ent931 = ms1Ents.Find(x => x.CurTime == time931);
                //if (ent931 == null) continue;
                //DateTime time932 = new DateTime(time.Year, time.Month, time.Day, 9, 32, 0);
                //var ent932 = ms1Ents.Find(x => x.CurTime == time932);
                //if (ent932 == null) continue;

                //// 开盘一分涨停。跳过
                //if (ent931.EndPrice >= price095P || ent931.StartPrice >= price095P) continue;
                //// 开盘低于-2点，跳过
                //if (ent931.StartPrice < price02DP) continue;
                ////低开一分钟下跌，跳过
                //if (ent931.EndPrice < ent931.StartPrice) continue;
                //if (ent931.StartPrice >= price02DP && ent931.StartPrice <= price00P)
                //{
                //    //低开两分钟，未上涨至2点以上，跳过
                //    if (ent932.EndPrice < price020P) continue;

                //    buyList.Add(new Tuple<DateTime, string, float>(time932, item.Code, ent932.EndPrice));
                //    continue;
                //}

                //// 高开3点，一分内为上涨
                //if (ent931.StartPrice >= price030P)
                //{
                //    buyList.Add(new Tuple<DateTime, string, float>(time931, item.Code, ent931.EndPrice));
                //    continue;
                //}

                //if(ent932.EndPrice > ent931.StartPrice && ent932.EndPrice >= price050P)
                //{
                //    buyList.Add(new Tuple<DateTime, string, float>(time932, item.Code, ent932.EndPrice));
                //    continue;
                //}
                //DateTime time933 = new DateTime(time.Year, time.Month, time.Day, 9, 33, 0);
                //var ent933 = ms1Ents.Find(x => x.CurTime == time933);
                //if (ent933 == null) continue;
                //if (ent933.EndPrice > ent932.EndPrice && ent933.EndPrice >= price050P)
                //{
                //    buyList.Add(new Tuple<DateTime, string, float>(time933, item.Code, ent933.EndPrice));
                //    continue;
                //}
                #endregion

                #region 规则3
                ////1. 时间10点到1点30
                ////2.三日内无涨停
                ////3.买入前无接近涨停，小幅震荡

                ////三日内无涨停
                //if (nowIndex < 5) continue;
                //var pre3List = dayEnts.GetRange(nowIndex - 3, 3);

                //if (pre3List.Find(x => x.HighPrice > x.ClsPrice / (1 + x.MarkUp / 100.0) * 1.095) != null) continue;

                //var pre5List = dayEnts.GetRange(nowIndex - 5, 5);

                //float tempMark = 0;
                //pre5List.ForEach(x => tempMark += x.MarkUp);

                //if (tempMark < -8) continue;

                //float m_95Price = dayEnts[nowIndex - 1].ClsPrice * 1.095f;
                //float m_5Price = dayEnts[nowIndex - 1].ClsPrice * 1.05f;
                //float m_De5Price = dayEnts[nowIndex - 1].ClsPrice * 0.95f;

                //var list = GpLocalDataHelper.GetDay1MSEntitiesByCode(time.Year, item.Code);
                //DateTime todtime931 = new DateTime(time.Year, time.Month, time.Day, 9, 31, 0);
                //var tod931Index = list.FindIndex(x => x.CurTime == todtime931);
                //if (tod931Index < 0) continue;
                //list = list.GetRange(tod931Index, 240);

                //int index931 = list.FindIndex(x => x.CurTime == new DateTime(time.Year, time.Month, time.Day, 9, 31, 0));
                //var list930_30 = list.GetRange(index931, 30);
                ////买入前无接近涨停，小幅震荡
                //if (list930_30.Find(x => x.EndPrice > m_5Price || x.EndPrice < m_De5Price) != null) continue;

                //// 时间10点到1点30
                //DateTime t100 = new DateTime(time.Year, time.Month, time.Day, 10, 0, 0);
                //DateTime t1330 = new DateTime(time.Year, time.Month, time.Day, 13, 30, 0);
                //int index100 = list.FindIndex(x => x.CurTime == t100);
                //var list100_120 = list.GetRange(index100, 120);

                //var buyInEnt = list100_120.FirstOrDefault(x => x.EndPrice >= m_95Price);
                //if (buyInEnt == null) continue;

                //buyList.Add(new Tuple<DateTime, string, float>(buyInEnt.CurTime, item.Code, buyInEnt.EndPrice));
                #endregion

                #region 规则4
                // 首板  五日无涨停  并且首板封板时间在收盘30分钟之前
                // 一字板不追，收盘前30分钟涨停不追
                // 涨停买入  分仓 5

                if (nowIndex < 8) continue;
                int num = 1;
                if (!string.IsNullOrEmpty(SpecialCodes))
                {
                    num = int.Parse(SpecialCodes);
                }
                bool isCon = true;
                for (int i = 0; i < num; i++)
                {
                    if (dayEnts[nowIndex - (i + 1)].MarkUp <= 9.8)
                    {
                        isCon = false;
                        break;
                    }
                }
                if (!isCon) continue;
                

                if (dayEnts[nowIndex].HighPrice <= dayEnts[nowIndex - 1].ClsPrice * 1.098) continue;
                if (dayEnts[nowIndex].PrePrice >= dayEnts[nowIndex - 1].ClsPrice * 1.098) continue;

                var pre5List = dayEnts.GetRange(nowIndex - (5 + num), 5);
                if (pre5List.Find(x => x.MarkUp >= 9.8) != null) continue;

                var list = GpLocalDataHelper.GetDay1MSEntitiesByCode(time.Year, item.Code);

                DateTime pretime931 = new DateTime(time.Year, dayEnts[nowIndex - 1].Time.Month, dayEnts[nowIndex - 1].Time.Day, 9, 31, 0);
                var pre931Index = list.FindIndex(x => x.CurTime == pretime931);
                if (pre931Index < 0) continue;
                var preList  = list.GetRange(pre931Index, 240);
                if (preList.FindIndex(x => x.HighPrice >= dayEnts[nowIndex - 2].ClsPrice * 1.098) >= 209)
                    continue;

                DateTime todtime931 = new DateTime(time.Year, time.Month, dayEnts[nowIndex].Time.Day, 9, 31, 0);
                var tod931Index = list.FindIndex(x => x.CurTime == todtime931);
                if (tod931Index < 0) continue;
                var todList = list.GetRange(tod931Index, 240);
                var fstTopIndex = todList.FindIndex(x => x.HighPrice >= dayEnts[nowIndex - 1].ClsPrice * 1.098);
                if (fstTopIndex >= 209)
                    continue;
                var curEnt = todList[fstTopIndex];
                buyList.Add(new Tuple<DateTime, string, float>(curEnt.CurTime, item.Code, curEnt.HighPrice));
                #endregion
            }

            Random random = new Random();
            buyList = buyList.OrderBy(x => random.Next()).ToList();
            foreach (var item in buyList)
            {
                if (m_Account.CurBuyInGps.Count >= m_Account.ValidBuyNum)
                    return;
                int validNum = m_Account.ValidBuyNum - m_Account.CurBuyInGps.Count;
                double curCash = Math.Floor(m_Account.Cash / (double)validNum);
                var tempGp = dicGpInfo[time].Find(x => x.Code == item.Item2);
                //float buyPrice = tempGp.PrePrice * (1 + item.Key);
                //buyPrice = float.Parse(buyPrice.ToString("F2"));
                float buyPrice = item.Item3;
                int count = (int)Math.Floor(curCash / (buyPrice * 100)) * 100;
                if (count == 0) continue;
                BuyGp(item.Item2, tempGp.Name, buyPrice, count, item.Item1);
            }

        }

        private void BuyGpExecute(DateTime time,string code,float buyPrice,DateTime buyTime)
        {
            if (m_Account.CurBuyInGps.Count >= m_Account.ValidBuyNum)
                return;
            int validNum = m_Account.ValidBuyNum - m_Account.CurBuyInGps.Count;
            double curCash = Math.Floor(m_Account.Cash / (double)validNum);
            var tempGp = dicGpInfo[time].Find(x => x.Code == code);
            int count = (int)Math.Floor(curCash / (buyPrice * 100)) * 100;
            if (count == 0) return;
            BuyGp(code, tempGp.Name, buyPrice, count, buyTime);
        }
        #endregion

        #region 业务方法
        private void InitCommand()
        {
            RunCommand = new DelegateCommand(RunExecute);
        }
        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //m_View.progressBar.Value = 0;
            //m_View.barText.Text = "";
        }

        private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //m_View.progressBar.Value = e.ProgressPercentage;

            //int currentTask = (int)e.UserState;
            //m_View.barText.Text = $"正在{barMsg}（{currentTask}/{infoNum}）";
        }
        private void RunExecute()
        {
            m_Account.Cash = Cash;
            m_Account.ValidBuyNum = ValidGpNum;
            m_Account.CurBuyInGps.Clear();
            m_Account.HisBuyInGps.Clear();
            MsgList.Clear();
            m_View.runBtn.Content = "运行ing...";
            m_View.runBtn.IsEnabled = false;

            if (!string.IsNullOrEmpty(SpecialCodes) && SpecialCodes.Length >= 6)
            {
                m_SelectedCodes = SpecialCodes.Split(';').ToList();
            }
            else
            {
                m_SelectedCodes = new List<string>();
            }
            TotalRunCount++;
            Thread thread = new Thread(Run);
            thread.Start();
        }
        private void Run()
        {
            try
            {
                DateTime startTime = new DateTime(CurYear,11, 1);
                DateTime endTime = new DateTime(CurYear, 12, 2);


                if (hasChangeYear)
                {
                    hasChangeYear = false;
                    dicGpInfo.Clear();
                    dicAllGpInfo.Clear();
                    while (startTime != endTime)
                    {
                        dicGpInfo.Add(startTime, new List<GpDayEntity>());
                        startTime = startTime.AddDays(1);
                    }
                    // 加载所有历史股票数据
                    InitGpData();
                }
                else
                {
                    if (dicAllGpInfo != null && dicAllGpInfo.Count > 0
    && dicGpInfo != null && dicGpInfo.Count > 0)
                    {

                    }
                    else
                    {
                        dicGpInfo.Clear();
                        dicAllGpInfo.Clear();
                        while (startTime != endTime)
                        {
                            dicGpInfo.Add(startTime, new List<GpDayEntity>());
                            startTime = startTime.AddDays(1);
                        }
                        // 加载所有历史股票数据
                        InitGpData();
                    }
                }


                // 加载历史分时数据
                //AlGpHelper.LoadHistoryMS5Info();

                List<string> IntentionList = new List<string>();

                startTime = new DateTime(CurYear, 11, 1);
                endTime = new DateTime(CurYear, 12, 2);
                // 开始循环操作
                while (startTime != endTime)
                {
                    DateTime tempTime = startTime;
                    startTime = startTime.AddDays(1);

                    if (dicGpInfo[tempTime].Count == 0) continue;

                    if (!string.IsNullOrEmpty(SpecialDay) && !string.IsNullOrEmpty(SpecialMonth))
                    {
                        if (tempTime == new DateTime(tempTime.Year, int.Parse(SpecialMonth), int.Parse(SpecialDay)))
                        {
                            MessageBox.Show("到达指定日期");
                        }
                    }
                    PossessGpExecute(tempTime);
                    SelectToBuyExecute(tempTime);
                    //SimpleAutoExecute(tempTime, ref IntentionList);

                    m_View.listBox.Dispatcher.Invoke(new Action(() =>
                    {
                        MsgList.Add(string.Format("日期【{0}】 今日资产【{1}】", tempTime, m_Account.MarkValue));

                    }));
                }
            }
            catch (Exception ex)
            {

                //MessageBox.Show(ex.Message);
            }
            m_View.listBox.Dispatcher.Invoke(new Action(() =>
            {
                m_View.runBtn.Content = "运行";
                m_View.runBtn.IsEnabled = true;
                TotalValue += m_Account.MarkValue;
                MsgList.Add(string.Format("总平均{0}", TotalValue/ TotalRunCount));
                m_View.listBox.SelectedIndex = m_View.listBox.Items.Count - 1;
            }));
        }
        private void InitGpData()
        {
            var files = Directory.GetFiles(System.IO.Path.Combine(CommonData.HisInfoFolderPath, CurYear.ToString()));
            var codes = GpLocalDataHelper.GetValidGpCodes();
            foreach (var item in files)
            {
                string code = item.Substring(item.Length - 11, 6);
                if (!codes.Contains(code)) continue;
                string json = File.ReadAllText(item);
                var strs = json.Split(';');
                List<GpDayEntity> list = new List<GpDayEntity>();
                foreach (var str in strs)
                {
                    var tempEnt = GpDayEntity.Create(str);
                    if (tempEnt != null)
                        list.Add(tempEnt);
                }

                if (list.Count == 0)
                {
                    continue;
                }
                List<float> day5List = new List<float>();
                List<float> day10List = new List<float>();
                List<float> day20List = new List<float>();
                List<float> day60List = new List<float>();
                // 计算均线
                for (int i = 0; i < list.Count; i++)
                {
                    day5List.Add(list[i].ClsPrice);
                    day10List.Add(list[i].ClsPrice);
                    day20List.Add(list[i].ClsPrice);
                    day60List.Add(list[i].ClsPrice);
                    if (day5List.Count == 6)
                    {
                        day5List.RemoveAt(0);
                    }
                    if (day5List.Count == 5)
                    {
                        float total5 = 0f;
                        day5List.ForEach(x => { total5 += x; });
                        list[i].Day5Price = (float)Math.Round(total5 / 5f, 2, MidpointRounding.AwayFromZero);
                    }
                    if (day10List.Count == 11)
                    {
                        day10List.RemoveAt(0);
                    }
                    if (day10List.Count == 10)
                    {
                        float total10 = 0f;
                        day10List.ForEach(x => { total10 += x; });
                        list[i].Day10Price = (float)Math.Round(total10 / 10f, 2, MidpointRounding.AwayFromZero);
                    }
                    if (day20List.Count == 21)
                    {
                        day20List.RemoveAt(0);
                    }
                    if (day20List.Count == 20)
                    {
                        float total20 = 0f;
                        day20List.ForEach(x => { total20 += x; });
                        list[i].Day20Price = (float)Math.Round(total20 / 20f, 2, MidpointRounding.AwayFromZero);
                    }
                    if (day60List.Count == 61)
                    {
                        day60List.RemoveAt(0);
                    }
                    if (day60List.Count == 60)
                    {
                        float total60 = 0f;
                        day60List.ForEach(x => { total60 += x; });
                        list[i].Day60Price = (float)Math.Round(total60 / 60f, 2, MidpointRounding.AwayFromZero);
                    }
                }
                dicAllGpInfo.Add(list[0].Code, list);
                foreach (var keyValue in dicGpInfo)
                {
                    var temp = list.Find(x => x.Time == keyValue.Key);
                    if (temp != null)
                        keyValue.Value.Add(temp);
                }
            }
        }


        /// <summary>
        /// 判断某个日期前三十个交易日是否有首板后下跌情况
        /// </summary>
        /// <param name="code"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        private bool HasOneTopDown(string code, DateTime time)
        {
            if (dicAllGpInfo.ContainsKey(code))
            {
                int index = dicAllGpInfo[code].FindIndex(x => x.Time == time);
                if (index >= 0)
                {
                    var startIndex = index - 100;
                    if (startIndex < 0)
                        startIndex = 0;
                    var tempList = dicAllGpInfo[code].GetRange(startIndex, index - startIndex);
                    var lastIndex = tempList.FindLastIndex(x => x.MarkUp > 9);
                    if (lastIndex > 0 && lastIndex < tempList.Count - 1)
                    {
                        if (tempList[lastIndex - 1].MarkUp < 8 && tempList[lastIndex + 1].ClsPrice < tempList[lastIndex + 1].PrePrice
                            && (tempList[lastIndex + 1].PrePrice - tempList[lastIndex + 1].ClsPrice) / tempList[lastIndex + 1].PrePrice > 0.03)
                            return true;
                    }
                }
            }
            return false;
        }
        private void BuyGp(string code, string name, float price, int count, DateTime time)
        {
            if (m_SelectedCodes != null && m_SelectedCodes.Count != 0)
            {
                if (m_SelectedCodes.Contains(code))
                    MessageBox.Show("指定股票买入");
            }

            BuyInGpEntity ent = new BuyInGpEntity();
            ent.BuyInPrice = price;
            ent.BuyInTime = time;
            ent.GpCount = count;
            ent.GpCode = code;
            ent.Name = name;
            m_Account.CurBuyInGps.Add(ent);
            m_Account.Cash -= price * count;

            m_View.listBox.Dispatcher.Invoke(new Action(() =>
            {
                MsgList.Add(string.Format("买入日期【{0}】，买入【{1}】（{2}）,买入价格【{3}】，数量【{4}】，总价【{5}】", time, name, code, price, count, price * count));

            }));
        }
        private void PayOutGp(BuyInGpEntity ent, float price, DateTime time)
        {
            if (m_SelectedCodes != null && m_SelectedCodes.Count != 0)
            {
                if (m_SelectedCodes.Contains(ent.GpCode))
                    MessageBox.Show("指定股票卖出");
            }

            ent.PayOutPrice = price;
            ent.PayOutTime = time;
            ent.IsPayOut = true;

            ent.Earnings = (float)Math.Round((ent.PayOutPrice - ent.BuyInPrice) * ent.GpCount, 2, MidpointRounding.AwayFromZero);
            m_Account.HisBuyInGps.Add(ent);
            m_Account.CurBuyInGps.Remove(ent);
            m_Account.Cash += price * ent.GpCount;
            m_View.listBox.Dispatcher.Invoke(new Action(() =>
            {
                MsgList.Add(string.Format("卖出日期【{0}】，卖出【{1}】（{2}）,卖出价格【{3}】，数量【{4}】，总价【{5}】，盈亏【{6}】",
   time, ent.Name, ent.GpCode, price, ent.GpCount, price * ent.GpCount, ent.Earnings));
            }));

        }
        #endregion

        #region 买入规则
        private bool m_EnableForLowStart = true;
        /// <summary>
        /// 低开开盘
        /// </summary>
        public bool EnableForLowStart
        {
            get { return m_EnableForLowStart; }
            set
            {
                m_EnableForLowStart = value;
                RaisePropertyChanged();
            }
        }

        private bool m_EnableForMarkDownInFive = true;
        /// <summary>
        /// 五分钟为下跌
        /// </summary>
        public bool EnableForMarkDownInFive
        {
            get { return m_EnableForMarkDownInFive; }
            set
            {
                m_EnableForMarkDownInFive = value;
                RaisePropertyChanged();
            }
        }
        private bool m_EnableForBreakDownInFive = true;
        /// <summary>
        /// 五分钟跌破均线
        /// </summary>
        public bool EnableForBreakDownInFive
        {
            get { return m_EnableForBreakDownInFive; }
            set
            {
                m_EnableForBreakDownInFive = value;
                RaisePropertyChanged();
            }
        }
        private bool m_EnableForBreakDownInTen = true;
        /// <summary>
        /// 十分钟跌破均线
        /// </summary>
        public bool EnableForBreakDownInTen
        {
            get { return m_EnableForBreakDownInTen; }
            set
            {
                m_EnableForBreakDownInTen = value;
                RaisePropertyChanged();
            }
        }
        private bool m_EnableForStartIn2_7 = true;
        /// <summary>
        /// 开盘涨幅2-7
        /// </summary>
        public bool EnableForStartIn2_7
        {
            get { return m_EnableForStartIn2_7; }
            set
            {
                m_EnableForStartIn2_7 = value;
                RaisePropertyChanged();
            }
        }
        #endregion
        #region 卖出规则
        #endregion
        #region 选股规则
        private bool m_EnableForTopOneDay = true;
        /// <summary>
        /// 当日涨停
        /// </summary>
        public bool EnableForTopOneDay
        {
            get { return m_EnableForTopOneDay; }
            set
            {
                m_EnableForTopOneDay = value;
                RaisePropertyChanged();
            }
        }

        private bool m_EnableForTopTwoDay;
        /// <summary>
        /// 连续两日涨停
        /// </summary>
        public bool EnableForTopTwoDay
        {
            get { return m_EnableForTopTwoDay; }
            set
            {
                m_EnableForTopTwoDay = value;
                RaisePropertyChanged();
            }
        }
        private bool m_EnableForTopOneDayWithNiceHistory;
        /// <summary>
        /// 连续两日涨停
        /// </summary>
        public bool EnableForTopOneDayWithNiceHistory
        {
            get { return m_EnableForTopOneDayWithNiceHistory; }
            set
            {
                m_EnableForTopOneDayWithNiceHistory = value;
                RaisePropertyChanged();
            }
        }
        #endregion
    }
}
